import os
import sys

from flask import Flask, send_file, abort, render_template_string

app = Flask(__name__)
sharePath = './'
nowPathList = []


def get_html_template():
  return '''
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>文件共享</title>
        <style>
            body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
            h1 { color: #333; }
            a { text-decoration: none; color: #0066cc; }
            a:hover { text-decoration: underline; }
            .file-list { list-style-type: none; padding: 0; }
            .file-list li { margin-bottom: 10px; }
            .folder { color: #4a86e8; }
            .file { color: #6aa84f; }
            .preview { max-width: 200px; max-height: 200px; margin-top: 10px; display: none; }
            #preview-toggle { margin-bottom: 20px; }
        </style>
    </head>
    <body>
        <h1>文件共享</h1>
        <button id="preview-toggle">开启图片预览</button>
        <ul class="file-list">
            {{ file_list | safe }}
        </ul>
        <script>
            const previewToggle = document.getElementById('preview-toggle');
            const fileList = document.querySelector('.file-list');
            let previewEnabled = false;

            previewToggle.addEventListener('click', () => {
                previewEnabled = !previewEnabled;
                previewToggle.textContent = previewEnabled ? '关闭图片预览' : '开启图片预览';
                const previews = document.querySelectorAll('.preview');
                previews.forEach(preview => {
                    preview.style.display = previewEnabled ? 'block' : 'none';
                });
            });
        </script>
    </body>
    </html>
    '''


def generate_file_list():
  files = os.listdir(os.path.join(sharePath, *nowPathList))
  parent = "/".join(nowPathList[:-1])
  result = [f'<li><a href="/{parent}">📂 ..</a></li>']

  nowPath = '/'.join(nowPathList)
  files = sorted(files, key=lambda f: (not os.path.isdir(os.path.join(sharePath, nowPath, f)), f.lower()))

  for file in files:
    full_path = os.path.join(sharePath, nowPath, file)
    is_dir = os.path.isdir(full_path)
    icon = '📂' if is_dir else '📄'
    css_class = 'folder' if is_dir else 'file'
    href = f'/{os.path.join(nowPath, file)}'.replace('\\', '/')

    if not is_dir and file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
      css_class += ' image'
      preview = f'<img src="{href}" class="preview" alt="{file}">'
    else:
      preview = ''

    result.append(f'<li><a href="{href}" class="{css_class}">{icon} {file}</a>{preview}</li>')

  return "\n".join(result)


@app.route('/')
def index():
  global nowPathList
  nowPathList.clear()
  return render_template_string(get_html_template(), file_list=generate_file_list())


@app.route('/favicon.ico')
def favicon():
  return send_file('favicon.ico')


@app.route('/<path:path>')
def goto(path):
  global nowPathList
  full_path = os.path.join(sharePath, path)

  if not os.path.exists(full_path):
    abort(404)

  if os.path.isdir(full_path):
    nowPathList = path.split('/')
    return render_template_string(get_html_template(), file_list=generate_file_list())

  return send_file(full_path)


def get_args(key, default=None):
  if key not in sys.argv:
    return default
  return sys.argv[sys.argv.index(key) + 1]


if __name__ == '__main__':
  sharePath = get_args('-r') or (sys.argv[1] if len(sys.argv) > 1 else sharePath)
  app.run(host=get_args('-h', '0.0.0.0'), port=int(get_args('-p', '80')))
